﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Text;
using LeonardoNews.Models;
using LeonardoNews.Repositories;

namespace LeonardoNews.Controllers
{
    public class UserController : ApiController
    {
        private HttpResponseMessage PerformOperation<T>(Func<T> action)
        {
            try
            {
                var result = action();
                return Request.CreateResponse(HttpStatusCode.OK, result);
            }
            catch (Exception ex)
            {
                return BuildErrorResponse(ex.Message);
            }
        }

        private HttpResponseMessage BuildErrorResponse(string message)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, message);
        }

        [HttpPost]
        [ActionName("register")]
        public HttpResponseMessage RegisterUser(User user)
        {
            var responseMsg = this.PerformOperation(() =>
            {
                UsersRepository.CreateUser(user.Username, user.AuthKey);
                var sessionKey = UsersRepository.LoginUser(user.Username, user.AuthKey);
                return new User()
                {
                    Username = user.Username,
                    SessionKey = sessionKey
                };
            });
            return responseMsg;
        }

        [HttpPost]
        [ActionName("login")]
        public HttpResponseMessage LoginUser(User user)
        {
            var responseMsg = this.PerformOperation(() =>
            {
                string nickname = string.Empty;
                var sessionKey = UsersRepository.LoginUser(user.Username, user.AuthKey);
                return new User()
                {
                    Username = user.Username,
                    SessionKey = sessionKey
                };
            });
            return responseMsg;
        }

        [HttpGet]
        [ActionName("logout")]
        public HttpResponseMessage LogoutUser(string sessionKey)
        {
            HttpResponseMessage responseMsg = this.PerformOperation(() =>
            {
                UsersRepository.LogoutUser(sessionKey);

                return Request.CreateResponse(HttpStatusCode.OK);  // inache ne buildva
            });
            return responseMsg;
        }

        [HttpGet]
        [ActionName("scores")]
        public HttpResponseMessage GetAllUsers(string sessionKey)
        {
            var responseMsg = this.PerformOperation(() =>
            {
                UsersRepository.LoginUser(sessionKey);
                var users = UsersRepository.GetAllUsers();

                return users;
            });

            return responseMsg;
        }
    }
}